<template>
  <div class="profile-wrapper">
    <!-- 顶部卡片：头像 + 昵称 -->
    <el-card class="profile-card">
      <div class="avatar-box">
        <div class="avatar-container">
          <el-avatar :size="120" :src="form.avatar" @error="handleAvatarError" class="user-avatar">
            <UserFilled />
          </el-avatar>
          <div class="avatar-buttons-container">
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadAvatarReq"
              accept="image/*"
              drag
            >
              <el-button type="primary" size="small" class="upload-btn">
                <el-icon style="font-size: 12px"><Camera /></el-icon>
                更换头像
              </el-button>
            </el-upload>
            <el-button
              v-if="form.avatar"
              type="danger"
              size="small"
              class="delete-btn"
              @click="deleteAvatar"
            >
              <el-icon style="font-size: 12px"><Delete /></el-icon>
              删除头像
            </el-button>
          </div>
        </div>
      </div>

      <div class="user-info">
        <h2>{{ form.username || '未设置昵称' }}</h2>
        <p>{{ form.email || '未设置邮箱' }}</p>
        <p v-if="userId" class="user-id">用户ID: {{ userId }}</p>
      </div>
    </el-card>

    <!-- 基本信息 -->
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span>基本信息</span>
          <el-button type="primary" size="small" @click="submitForm"> 保存 </el-button>
        </div>
      </template>

      <el-form
        ref="profileForm"
        :model="form"
        :rules="rules"
        label-width="80px"
        label-position="top"
      >
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12">
            <el-form-item label="昵称" prop="username">
              <el-input v-model="form.username" maxlength="20" show-word-limit />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12">
            <el-form-item label="手机" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" maxlength="11" />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24">
            <el-form-item label="简介">
              <el-input
                v-model="form.bio"
                type="textarea"
                :rows="3"
                maxlength="200"
                show-word-limit
                placeholder="介绍一下自己吧～"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 修改密码按钮 -->
    <el-card class="pwd-card">
      <el-button type="warning" @click="showPwdDrawer = true"> 修改密码 </el-button>
    </el-card>

    <!-- 修改密码抽屉 -->
    <el-drawer v-model="showPwdDrawer" title="修改密码" direction="rtl" size="380px">
      <el-form ref="pwdForm" :model="pwd" :rules="pwdRules" label-width="80">
        <el-form-item label="原密码" prop="oldPassword">
          <!-- prop 改为 oldPassword -->
          <el-input v-model="pwd.oldPassword" type="password" show-password />
          <!-- v-model 改为 oldPassword -->
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <!-- prop 改为 newPassword -->
          <el-input v-model="pwd.newPassword" type="password" show-password />
          <!-- v-model 改为 newPassword -->
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPwd">
          <el-input v-model="pwd.confirmPwd" type="password" show-password />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitPwd">确认修改</el-button>
          <el-button @click="showPwdDrawer = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 头像预览对话框 -->
    <el-dialog
      v-model="avatarPreviewVisible"
      title="头像预览"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="avatar-preview">
        <div class="preview-container">
          <img
            v-if="avatarPreviewUrl"
            :src="avatarPreviewUrl"
            alt="头像预览"
            class="preview-image"
          />
          <div class="preview-info">
            <p>请确认头像图片是否符合要求</p>
            <ul>
              <li>支持格式：JPG、PNG、GIF、WebP</li>
              <li>文件大小：不超过2MB</li>
              <li>建议尺寸：200x200像素以上</li>
            </ul>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelAvatarUpload" :disabled="uploading">取消</el-button>
          <el-button
            type="primary"
            @click="confirmAvatarUpload"
            :loading="uploading"
            :disabled="uploading"
          >
            {{ uploading ? '上传中...' : '确认上传' }}
          </el-button>
        </div>
        <div v-if="uploading" class="upload-progress">
          <el-progress :percentage="uploadProgress" :show-text="false" :stroke-width="4" />
          <p class="progress-text">正在上传头像...</p>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Camera, Delete } from '@element-plus/icons-vue'
import { userApi, uploadApi, personalApi } from '@/api'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
const router = useRouter()
/* 1. 获取当前用户 ID - 增强版 */
const getUserId = () => {
  // 优先级：localStorage > store.userInfo.id > store.userInfo.userId
  const localStorageId = localStorage.getItem('userId')
  const storeId = userStore.userInfo?.id
  const storeUserId = userStore.userInfo?.userId

  const finalId = localStorageId || storeId || storeUserId

  console.log('🔍 用户ID获取详情:', {
    localStorageId,
    storeId,
    storeUserId,
    finalId,
    userStoreInfo: userStore.userInfo,
  })

  return finalId
}

const userId = getUserId()

/* 2. 表单数据 */
const form = reactive({
  avatar: '',
  username: '',
  email: '',
  phoneNumber: '',
  bio: '',
})

const rules = {
  username: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  email: [{ type: 'email', message: '邮箱格式错误', trigger: 'blur' }],
  phoneNumber: [{ pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur' }],
}

/* 3. 加载个人资料 - 增强版 */
onMounted(async () => {
  // 重新获取用户ID（可能在组件初始化后store已更新）
  const currentUserId = getUserId()
  console.log('📋 开始加载个人资料，当前用户ID:', currentUserId)

  // 首先尝试从store获取用户信息
  if (userStore.userInfo) {
    form.username = userStore.userInfo.username || ''
    form.email = userStore.userInfo.email || ''
    form.avatar = userStore.userInfo.avatar || ''
    form.phoneNumber = userStore.userInfo.phoneNumber || ''
    form.bio = userStore.userInfo.bio || ''
    console.log('📋 已从store加载基础用户信息')
  }

  // 如果没有用户ID，尝试初始化用户状态
  if (!currentUserId) {
    console.warn('⚠️ 用户ID不存在，尝试重新初始化用户状态')
    userStore.initUserState()

    // 重新获取用户ID
    const retryUserId = getUserId()
    if (!retryUserId) {
      console.error('❌ 无法获取用户ID，可能需要重新登录')
      ElMessage.warning('无法获取用户信息，请重新登录')
      return
    }
    console.log('✅ 重新获取到用户ID:', retryUserId)
  }

  try {
    // 使用最新的用户ID
    const finalUserId = currentUserId || getUserId()
    if (!finalUserId) {
      throw new Error('无法获取有效的用户ID')
    }

    // 使用personalApi.getProfile()来获取用户信息
    console.log('📡 开始获取个人信息，用户ID:', finalUserId)
    const userData = await personalApi.getProfile(finalUserId)
    console.log('📡 个人信息接口返回:', userData)

    // 特别检查phoneNumber字段
    console.log('PhoneNumber字段详情:', {
      hasPhoneNumber: 'phoneNumber' in userData,
      phoneValue: userData.phoneNumber,
      phoneType: typeof userData.phoneNumber,
    })

    // 合并数据，确保所有字段正确
    Object.assign(form, {
      avatar: userData.avatar || userStore.userInfo?.avatar || form.avatar || '',
      username: userData.username || userStore.userInfo?.username || form.username || '',
      email: userData.email || userStore.userInfo?.email || form.email || '',
      phoneNumber:
        userData.phoneNumber || userStore.userInfo?.phoneNumber || form.phoneNumber || '',
      bio: userData.bio || userStore.userInfo?.bio || form.bio || '',
    })

    // 如果后端返回了新的用户信息，更新store
    if (userData.username || userData.email) {
      userStore.userInfo = {
        ...userStore.userInfo,
        username: userData.username || userStore.userInfo?.username,
        email: userData.email || userStore.userInfo?.email,
        avatar: userData.avatar || userStore.userInfo?.avatar,
        phoneNumber: userData.phoneNumber || userStore.userInfo?.phoneNumber,
        bio: userData.bio || userStore.userInfo?.bio,
      }
      localStorage.setItem('userInfo', JSON.stringify(userStore.userInfo))
    }

    ElMessage.success('个人信息加载成功')
  } catch (error) {
    console.error('获取个人信息错误:', error)

    // 如果获取失败，但store中有数据，不显示错误
    if (userStore.userInfo && (userStore.userInfo.username || userStore.userInfo.email)) {
      console.log('使用store中的用户信息')
    } else {
      ElMessage.warning('获取个人信息失败，请检查网络连接')
    }
  }
})

/* 4. 头像上传 */
const beforeAvatarUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  // 创建预览URL并显示预览对话框
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarPreviewUrl.value = e.target.result
    pendingAvatarFile.value = file
    avatarPreviewVisible.value = true
  }
  reader.readAsDataURL(file)

  return false // 阻止自动上传，改为手动确认
}

const uploadAvatarReq = async ({ file }) => {
  // 这个方法现在不会被调用，因为我们返回了false
  console.log('uploadAvatarReq called with:', file)
}

// 取消头像上传
const cancelAvatarUpload = () => {
  avatarPreviewVisible.value = false
  avatarPreviewUrl.value = ''
  pendingAvatarFile.value = null
  uploading.value = false
  uploadProgress.value = 0
}

// 确认头像上传
const confirmAvatarUpload = async () => {
  if (!pendingAvatarFile.value) {
    ElMessage.error('没有待上传的文件')
    return
  }

  uploading.value = true
  uploadProgress.value = 0

  // 模拟上传进度
  const progressInterval = setInterval(() => {
    if (uploadProgress.value < 90) {
      uploadProgress.value += 10
    }
  }, 200)

  try {
    // 直接使用base64方案，避免接口问题
    const reader = new FileReader()
    reader.onload = (e) => {
      const base64Data = e.target.result
      form.avatar = base64Data

      // 更新用户store中的头像信息
      if (userStore.userInfo) {
        userStore.userInfo.avatar = base64Data
        localStorage.setItem('userInfo', JSON.stringify(userStore.userInfo))
      }

      // 尝试更新个人资料到后端
      const currentUserId = getUserId()
      if (currentUserId) {
        const updateData = {
          email: form.email,
          phoneNumber: form.phoneNumber,
          avatar: base64Data,
          bio: form.bio,
        }
        personalApi.updateProfile(currentUserId, updateData).catch((err) => {
          console.warn('更新个人资料失败，但头像已保存到本地:', err)
        })
      }

      ElMessage.success('头像上传成功')
      avatarPreviewVisible.value = false
      avatarPreviewUrl.value = ''
      pendingAvatarFile.value = null
      uploading.value = false
      uploadProgress.value = 100

      setTimeout(() => {
        uploadProgress.value = 0
      }, 500)
    }
    reader.readAsDataURL(pendingAvatarFile.value)
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败，请重试')
    uploading.value = false
    uploadProgress.value = 0
  } finally {
    clearInterval(progressInterval)
  }
}

// 头像加载错误处理
const handleAvatarError = () => {
  // 头像加载失败时使用默认头像
  console.log('头像加载失败，使用默认头像')
  // 不修改form.avatar，让el-avatar组件显示默认的UserFilled图标
}

// 删除头像
const deleteAvatar = async () => {
  try {
    await ElMessageBox.confirm('确定要删除当前头像吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    form.avatar = ''

    // 更新用户store中的头像信息
    if (userStore.userInfo) {
      userStore.userInfo.avatar = ''
      localStorage.setItem('userInfo', JSON.stringify(userStore.userInfo))
    }

    // 保存到后端
    const currentUserId = getUserId()
    if (currentUserId) {
      const updateData = {
        email: form.email,
        phoneNumber: form.phoneNumber,
        avatar: form.avatar,
        bio: form.bio,
      }
      await personalApi.updateProfile(currentUserId, updateData)
    }

    ElMessage.success('头像删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除头像失败')
    }
  }
}

/* 5. 保存信息 */
const profileForm = ref()
const submitForm = async () => {
  try {
    console.log('开始保存个人信息...')
    await profileForm.value.validate()

    // 检查用户ID
    const currentUserId = getUserId()
    if (!currentUserId) {
      console.error('❌ 保存时无法获取用户ID')
      throw new Error('用户ID不存在，无法保存')
    }
    console.log('💾 使用用户ID保存:', currentUserId)

    // 只发送后端需要的字段
    const updateData = {
      email: form.email,
      phoneNumber: form.phoneNumber,
      avatar: form.avatar,
      bio: form.bio,
    }

    console.log('💾 准备发送的更新数据:', updateData)
    console.log('💾 更新用户ID:', currentUserId)

    const result = await personalApi.updateProfile(currentUserId, updateData)
    console.log('更新结果:', result)

    ElMessage.success('保存成功')

    // 更新本地store
    if (userStore.userInfo) {
      userStore.userInfo = {
        ...userStore.userInfo,
        email: form.email,
        phoneNumber: form.phoneNumber,
        avatar: form.avatar,
        bio: form.bio,
      }
      localStorage.setItem('userInfo', JSON.stringify(userStore.userInfo))
    }
  } catch (e) {
    console.error('保存失败详情:', e)
    const errorMsg = e.response?.data?.message || e.response?.data?.msg || e.message || '保存失败'
    ElMessage.error(errorMsg)
  }
}

/* 6. 头像预览 */
const avatarPreviewVisible = ref(false)
const avatarPreviewUrl = ref('')
const pendingAvatarFile = ref(null)
const uploading = ref(false)
const uploadProgress = ref(0)

/* 7. 修改密码 */
const showPwdDrawer = ref(false)
const pwd = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPwd: '',
})
const pwdRules = {
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [
    { required: true, min: 6, message: '新密码至少 6 位', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/,
      message: '密码需包含大小写字母和数字',
      trigger: 'blur',
    },
  ],
  confirmPwd: [
    {
      validator: (_, v) =>
        v === pwd.newPassword ? Promise.resolve() : Promise.reject('两次密码不一致'),
      trigger: 'blur',
    },
  ],
}
const pwdForm = ref()
const submitPwd = async () => {
  try {
    await pwdForm.value.validate()
    // 1. 构造与后端匹配的参数结构
    const passwordData = {
      oldPassword: pwd.oldPassword, // 对应后端 OldPassword
      newPassword: pwd.newPassword, // 对应后端 NewPassword
    }
    // 检查用户ID
    const currentUserId = getUserId()
    if (!currentUserId) {
      throw new Error('用户ID不存在，无法修改密码')
    }

    // 2. 调用正确的接口路径（确保与后端路由一致）
    await personalApi.changePassword(currentUserId, passwordData)
    ElMessage.success('密码已更新，请重新登录')
    // 清除本地存储并跳转到登录页
    localStorage.removeItem('token')
    userStore.token = null
    localStorage.removeItem('userId')
    router.push('/login')
    showPwdDrawer.value = false
    // 3. 清空表单
    pwd.oldPassword = ''
    pwd.newPassword = ''
    pwd.confirmPwd = ''
  } catch (e) {
    // 优化错误信息显示
    const errorMsg = e.response?.data?.message || e.message || '更新失败'
    ElMessage.error(errorMsg)
  }
}
</script>

<style scoped>
.profile-wrapper {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.profile-card,
.info-card,
.pwd-card {
  margin-bottom: 20px;
}

.avatar-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.user-avatar {
  border: 4px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  display: block;
}

.avatar-buttons-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: center;
  padding: 12px;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  background: #fafafa;
  min-width: 120px;
}

.avatar-uploader {
  background: transparent;
}

.upload-btn {
  background: #409eff;
  border: 1px solid #409eff;
  color: white;
  transition: all 0.3s ease;
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 11px;
  width: 100%;
  min-width: 100px;
}

.upload-btn:hover {
  background: #66b1ff;
  border-color: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.delete-btn {
  background: #f56c6c;
  border: 1px solid #f56c6c;
  color: white;
  transition: all 0.3s ease;
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 11px;
  width: 100%;
  min-width: 100px;
}

.delete-btn:hover {
  background: #f78989;
  border-color: #f78989;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.3);
}

.avatar-preview {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 250px;
}

.preview-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.preview-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border: 2px solid #e4e7ed;
}

.preview-info {
  text-align: center;
  color: #606266;
}

.preview-info p {
  margin: 0 0 12px 0;
  font-weight: 500;
}

.preview-info ul {
  margin: 0;
  padding-left: 20px;
  text-align: left;
}

.preview-info li {
  margin-bottom: 4px;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
}

.upload-progress {
  margin-top: 16px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.progress-text {
  margin: 8px 0 0 0;
  text-align: center;
  color: #606266;
  font-size: 14px;
}

.user-info h2 {
  margin: 0;
  font-size: 20px;
}

.user-info p {
  margin: 4px 0 0;
  color: #909399;
}

.user-id {
  font-size: 12px;
  color: #c0c4cc;
  margin-top: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 移动端 */
@media (max-width: 768px) {
  .profile-wrapper {
    padding: 10px;
  }

  .avatar-buttons-container {
    padding: 12px;
    min-width: 120px;
  }

  .upload-btn,
  .delete-btn {
    padding: 6px 12px;
    font-size: 11px;
    min-width: 100px;
  }
}
</style>
